<?php

namespace app\api\controller;

use app\api\model\page\Page as AppPage;
use app\api\model\settings\Setting as SettingModel;
use app\common\enum\settings\SettingEnum;
use app\common\model\app\AppUpdate as AppUpdateModel;
use app\common\model\user;
use app\common\model\supplier\Service as ServiceModel;
use app\api\model\plus\chat\Chat as ChatModel;
use think\facade\Request;
use think\facade\Db;

/**
 * 页面控制器 

 */
class Index extends Controller
{
    /**
     * 首页
     */

    public function index($page_id = null, $url = '')
    {
		
		
        // 页面元素  $this->request->param('token')
        $data = AppPage::getPageData($this->getUser(false), $page_id);
        //消息条数 fenleifen
		$chag_id=Db::name('category')->where(["parent_id"=>Request::param('fenleifen')])->field('parent_id')->find()['parent_id']?:Db::name('category')->where(["parent_id"=>0])->find()['category_id'];
        $chaerji =Db::name('category')->where(["parent_id"=>$chag_id])->select();
		$chaerji_img =Db::name('category')->where(["category_id"=>Request::param('fenleifen_index')?:$chaerji[0]['category_id']])->field('image_id,jiage,eweijiage,jiage1,eweijiage1,jiage2,eweijiage2')->find(); 
        // 订单进行中 && 未付款
	    $countde = Db::name('order')->where(['user_id'=>$this->getUser(false)['user_id'],'order_status'=>10,'pay_status'=>10])->count();
		 
		
		 // if($countde>3){
			 // $data =0;
			      // return $this->renderSuccess('', compact('data'));
		 // }
		
		
		// dump($this->getUser(false)['user_id']);
		
		$Chat = new ChatModel;
        $data['msgNum'] = $Chat->mCount($this->getUser(false));
        $data['setting'] = array(
            'collection' => SettingModel::getItem('collection'),
            'officia' => SettingModel::getItem('officia'),
            'dingdanfenlei' => Db::name('category')->where(["parent_id"=>0])->select(),//1级分类
            'erjifenlei' => $chaerji,//二级分类  chaerji_jiage
            'chaerji_img' => 'https://xiaoma.ozhong.vip/uploads/'.Db::name('upload_file')->where(["file_id"=>$chaerji_img['image_id']])->field('save_name')->find()['save_name'],//二级分类tupian


            'chaerji_jiage' => $countde <=3 || $this->getUser(false)['user_id'] == '10441' || $this->getUser(false)['user_id'] == '10448'?$chaerji_img['jiage']:0,//二级分类价格
            'eweijiage' => $countde <=3 || $this->getUser(false)['user_id'] == '10441'?$chaerji_img['eweijiage']:0,//额外价格

            'chaerji_jiage1' => $countde <=3?$chaerji_img['jiage1']:0,//二级分类价格
            'eweijiage1' => $countde <=3  || $this->getUser(false)['user_id'] == '10441' || $this->getUser(false)['user_id'] == '10448'?$chaerji_img['eweijiage1']:0,//额外价格
            'chaerji_jiage2' => $countde <=3  || $this->getUser(false)['user_id'] == '10441' || $this->getUser(false)['user_id'] == '10448'?$chaerji_img['jiage2']:0,//二级分类价格
            'eweijiage2' => $countde <=3  || $this->getUser(false)['user_id'] == '10441' || $this->getUser(false)['user_id'] == '10448'?$chaerji_img['eweijiage2']:0,//额外价格
            'kefudianhua' => SettingModel::getItem('store')['namemobile'],//二级分类客服电话  dingdanfenlei
            'qinbugonglishu' => SettingModel::getItem('store')['qinbugonglishu'],//起步公里数  ;
            'homepush' => SettingModel::getItem('homepush'),
            'bobaode' => SettingModel::getItem('store')['bobaode'],
            'shouye_image' => SettingModel::getItem('store')['shouye_image'],
            'erweima_image' => SettingModel::getItem('store')['erweima_image'],
            'store' =>  SettingModel::getItem('store'),
        );
        // 扫一扫参数
        $data['signPackage'] = $this->getScanParams($url)['signPackage'];
		
		  $data['pingjiasde'] = Db::name('yonghu_pingjia')->select();
		
        return $this->renderSuccess('', $data);
    }

    /**
     * 首页
     */
    public function diy($page_id = null, $url = '')
    {
        // 页面元素
        $data = AppPage::getPageData($this->getUser(false), $page_id);
        // 微信公众号分享参数
        $data['share'] = $this->getShareParams($url, $data['page']['params']['share_title'], $data['page']['params']['share_title'], '/pages/diy-page/diy-page', $data['page']['style']['toplogo']);
        return $this->renderSuccess('', $data);
    }

    // 公众号客服
    public function mpService($shop_supplier_id)
    {
        $mp_service = ServiceModel::detail($shop_supplier_id);
        return $this->renderSuccess('', compact('mp_service'));
    }

    //底部导航
    public function nav()
    {
        $data['vars'] = SettingModel::getItem(SettingEnum::NAV);
        $data['theme'] = SettingModel::getItem(SettingEnum::THEME);
        $data['points_name'] = SettingModel::getPointsName();
        return $this->renderSuccess('', $data);
    }

    // app更新
    public function update($name, $version, $platform)
    {
        $result = [
            'update' => false,
            'wgtUrl' => '',
            'pkgUrl' => '',
        ];
        try {
            $model = AppUpdateModel::getLast();
            if ($platform == 'android') {
                $compare_version = $model['version_android'];
            } else {
                $compare_version = $model['version_ios'];
            }
            if ($model && str_replace('.', '', $version) < str_replace('.', '', $compare_version)) {
                $currentVersions = explode('.', $version);
                $resultVersions = explode('.', $compare_version);

                if ($currentVersions[0] < $resultVersions[0]) {
                    // 说明有大版本更新
                    $result['update'] = true;
                    $result['pkgUrl'] = $platform == 'android' ? $model['pkg_url_android'] : $model['pkg_url_ios'];
                    log_write('大版本');
                } else {
                    // 其它情况均认为是小版本更新
                    $result['update'] = true;
                    $result['wgtUrl'] = $model['wgt_url'];
                    log_write('小版本' . $result['wgtUrl']);
                }
            }
        } catch (\Exception $e) {

        }
        return $this->renderSuccess('', compact('result'));
    }

    /**
     * 定时任务：更新轨迹
     * @return
     */
    public function updateTrack()
    {
        // 获取每个 dingdn_id 下 status=0 的最小 index 对应记录
        $subQuery = Db::name('rengongguiji')
            ->where('status', '=', 0)
            // 排除同一 dingdn_id 下存在 status = 2 的记录
            ->whereNotIn('dingdn_id', function ($query) {
                $query->name('rengongguiji')->where('status', 2)->fieldRaw('dingdn_id');
            })
            ->fieldRaw('dingdn_id, MIN(`index`) AS min_index')
            ->group('dingdn_id')
            ->buildSql();

        $tracks = Db::name('rengongguiji')->alias('t1')
            ->join([$subQuery => 't2'], 't1.dingdn_id = t2.dingdn_id AND t1.`index` = t2.min_index')
            ->field('t1.id')
            ->select()
            ->toArray();

        $ids = array_column($tracks, 'id');
        if (!empty($ids)) {
            Db::name('rengongguiji')->where('id','in',$ids)->update(['status' => 1]);
        }
        return $this->renderSuccess('', compact('ids'));
 
     }

     

}
